package com.clp.protocol.core.client;

import com.clp.protocol.core.async.NettyAsyncSupport;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.EventExecutorGroup;
import io.netty.util.concurrent.Promise;

import java.io.Closeable;

/**
 * 内嵌Netty框架启动相关类
 */
public class NettyClient implements NettyConnector, NettyAsyncSupport, Closeable {
    private final EventLoopGroup eventLoopGroup;

    public NettyClient() {
        this.eventLoopGroup = new NioEventLoopGroup();
    }

    @Override
    public EventExecutor scheduledExecutorService() {
        return eventLoopGroup.next();
    }

    @Override
    public <T> Promise<T> createPromise(Class<T> clazz) {
        return new DefaultPromise<>(eventLoopGroup.next());
    }

    @Override
    public ChannelFuture connect(ChannelInitializer<SocketChannel> aInitializer, String remoteHost, int remotePort) {
        checkNotClosed();
        if (aInitializer == null) throw new NullPointerException("The initializer is null");
        return newBootstrap().handler(aInitializer).connect(remoteHost, remotePort);
    }

    private Bootstrap newBootstrap() {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true);
        return bootstrap;
    }

    @Override
    public ChannelFuture connect(ChannelInitializer<SocketChannel> aInitializer, String localHost, int localPort, String remoteHost, int remotePort) {
        checkNotClosed();
        if (aInitializer == null) throw new NullPointerException("The initializer is null");
        return newBootstrap().handler(aInitializer).localAddress(localHost, localPort).connect(remoteHost, remotePort);
    }

    private void checkNotClosed() {
        if (isClosed()) throw new IllegalStateException("Can not connect because netty client is closed");
    }

    public boolean isClosed() {
        return eventLoopGroup.isShutdown();
    }

    /**
     * 关闭客户端
     */
    @Override
    public void close() {
        // 停止BootStrap
        try {
            if (!eventLoopGroup.isShutdown()) {
                eventLoopGroup.shutdownGracefully().sync();
            }
        } catch(InterruptedException e){
            throw new RuntimeException(e);
        }
    }
}
